package com.example.myfoodrecipe.viewModel

import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.myfoodrecipe.data.local.LocalRepository
import com.example.myfoodrecipe.data.local.entity.RecipeEntity
import com.example.myfoodrecipe.data.model.FoodRecipe
import com.example.myfoodrecipe.data.remote.RemoteRepository
import com.example.myfoodrecipe.util.NetworkResult
import com.example.myfoodrecipe.util.showToast
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.concurrent.TimeoutException

class MainViewModel(application: Application): AndroidViewModel(application) {
    //retrofit请求对象
    private val remoteRepository = RemoteRepository()
    //room对象
    private val localRepository = LocalRepository(application)
    //首页的food：被观察的数据
    var recipes = MutableLiveData<NetworkResult<FoodRecipe>>()

    //从remoteRepository得到数据(被RecipeFragment调用)
    fun fetchFoodRecipe(type: String){
        //当前位于loading状态
        recipes.value = NetworkResult.Loading()

        //判断网络状态
        if (hasInternetConnection()){
            //先判断数据库里面有没有数据
            viewModelScope.launch{
                val cache = localRepository.getRecipes(type)
                //flow异步获得结果
                cache.collect {
                    if (it.isNotEmpty()){
                        val entity = it.first()
                        val data = entity.recipe
                        recipes.value = NetworkResult.Success(data)
                    }else{
                        //通过网络获取数据
                        try {
                            val response = remoteRepository.fetchFoodRecipe(type)
                            if (response.isSuccessful){
                                //从服务器获取数据成功，目前应处于success状态
                                recipes.value = NetworkResult.Success(response.body()!!)
                                //存入数据库
                                localRepository.insertRecipe(RecipeEntity(0,type,response.body()!!))
                            }else{
                                //从服务器获取数据失败，目前应处于error状态
                                recipes.value = NetworkResult.Error(response.message())
                            }
                        }catch (e: TimeoutException){
                            //由于网络状况获取数据超时
                            recipes.value = NetworkResult.Error("TIME OUT:${e.message}")
                        }
                    }
                    }
                }
        }else{
            //无网络
            showToast(getApplication(),"NO INTERNET CONNECTION")
            //从数据库读取
            viewModelScope.launch {
                val cache = localRepository.getRecipes(type)
                //flow异步获得结果
                cache.collect {
                    val entity = it.first()
                    val data = entity.recipe
                    recipes.value = NetworkResult.Success(data)
                }
            }

        }
    }

    //判断是否有网络连接
    private fun hasInternetConnection(): Boolean{
        //获取系统的网络连接管理器
        val connectivityManager = getApplication<Application>()
                .getSystemService(Context.CONNECTIVITY_SERVICE)
                as ConnectivityManager
        val activeNetwork = connectivityManager.activeNetwork ?: return false
        val capability = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false

        //返回true
        return when{
            capability.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            capability.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            capability.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
            else -> false
        }
    }
}